﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.System;
using Windows.UI.ApplicationSettings;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace BTN
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        DispatcherTimer _timer = new DispatcherTimer();

        public MainPage()
        {
            this.InitializeComponent();

            SettingsPane.GetForCurrentView().CommandsRequested += MainPage_CommandsRequested;
            this.webView.NavigationCompleted += webView_NavigationCompleted;

            _timer.Interval = new TimeSpan(0, 0, 1);
            _timer.Tick += timer_Tick;

            this.mediaPlayer.MediaOpened += mediaPlayer_MediaOpened;
            this.mediaPlayer.MediaEnded += mediaPlayer_MediaEnded;
            this.mediaPlayer.CurrentStateChanged += mediaPlayer_CurrentStateChanged;
            this.streamPlayer.CurrentStateChanged += mediaPlayer_CurrentStateChanged;

            EnableButtons(false, false, false);
        }

        void mediaPlayer_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            bool enablePlayButton = false;
            bool enablePauseButton = false;
            bool enableStopButton = false;

            MediaElementState currentState = MediaElementState.Closed;

            try 
            { 
                currentState = (IsStream == true) ? this.streamPlayer.CurrentState : this.mediaPlayer.CurrentState;
            }
            catch { }

            switch (currentState)
            {
                case MediaElementState.Buffering:
                    enableStopButton = true;
                    break;

                case MediaElementState.Closed:
                    break;

                case MediaElementState.Opening:
                    enableStopButton = true;
                    break;

                case MediaElementState.Paused:
                    enablePlayButton = true;
                    break;

                case MediaElementState.Playing:
                    enableStopButton = true;
                    enablePauseButton = true;
                    break;

                case MediaElementState.Stopped:
                    enablePlayButton = true;
                    break;
            }

            EnableButtons(enablePlayButton, enablePauseButton, enableStopButton);
        }

        private void EnableButtons(bool enablePlayButton, bool enablePauseButton, bool enableStopButton)
        {
            this.btnPlay.IsEnabled = enablePlayButton;
            this.btnPause.IsEnabled = enablePauseButton;
            this.btnStop.IsEnabled = enableStopButton;
        }

        async void MainPage_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            var privacyStatement = new SettingsCommand("privacy", "Privacy Statement", x => Launcher.LaunchUriAsync(
                    new Uri("http://www.sysnet.pe.kr/2/0/1649")));

            args.Request.ApplicationCommands.Clear();
            args.Request.ApplicationCommands.Add(privacyStatement);
        }

        bool _notFired = false;

        void timer_Tick(object sender, object e)
        {
            try
            {
                _notFired = true;

                if (this.mediaPlayer.CurrentState != MediaElementState.Playing)
                {
                    return;
                }

                this.sliderProgress.Value = this.mediaPlayer.Position.TotalSeconds;
            }
            finally
            {
                _notFired = false;
            }
        }

        void mediaPlayer_MediaOpened(object sender, RoutedEventArgs e)
        {
            this.sliderProgress.Maximum = this.mediaPlayer.NaturalDuration.TimeSpan.TotalSeconds;
            _timer.Start();
        }
        void mediaPlayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            _timer.Stop();
        }

        private void SeekToMediaPosition(object sender, RangeBaseValueChangedEventArgs args)
        {
            if (_notFired == true)
            {
                return;
            }

            int SliderValue = (int)this.sliderProgress.Value;

            TimeSpan ts = new TimeSpan(0, 0, 0, SliderValue);
            this.mediaPlayer.Position = ts;
        }

        async void webView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
        {
            string interceptPlayMovie = @"
            
                            (function () {
            
var links = document.getElementsByTagName('a');
var rtspText = 'rtsp://';

for (var i = 0; i < links.length; i ++) 
{
    var pos = links[i].href.indexOf(rtspText);
    if (pos == -1)
    {
        continue;
    }


    var newUrl = links[i].href.substr(pos + rtspText.length);
    newUrl = 'http://' + newUrl + '/playlist.m3u8';

    links[i].mediaUrl = newUrl;

    links[i].onclick = function() 
    {
         document.location.href = this.mediaUrl;
         return false;
    };
}
                            })();

                            ";

            await this.webView.InvokeScriptAsync("eval", new string[] { interceptPlayMovie });
        }

        const string _hostPath = "m.btn.co.kr";

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
        }

        async void webView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
        {
            if (mediaUrl != null)
            {
                mediaUrl.Text = "";
            }

            if (IsStream == false)
            {
                if (this.mediaPlayer != null)
                {
                    if (this.mediaPlayer.CurrentState == MediaElementState.Playing)
                    {
                        this.mediaPlayer.Stop();
                    }
                }
            }
            else
            {
                if (this.streamPlayer != null)
                {
                    if (this.streamPlayer.CurrentState == MediaElementState.Playing)
                    {
                        this.streamPlayer.Stop();
                    }
                }
            }

            if (args.Uri == null)
            {
                return;
            }

            string videoUrl = args.Uri.ToString();

            bool isStream = videoUrl.EndsWith("m3u8", StringComparison.OrdinalIgnoreCase) == true;
            if (isStream == false)
            {
                return;
            }

            args.Cancel = true;

            if (mediaUrl != null)
            {
                string localPath = GetFilePath(args.Uri.LocalPath);
                mediaUrl.Text = localPath;
            }

            this.mediaPlayer.Visibility = (isStream) ? Windows.UI.Xaml.Visibility.Collapsed : Windows.UI.Xaml.Visibility.Visible;
            this.streamPlayer.Visibility = (isStream) ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed;

            if (isStream == false)
            {
                this.sliderProgress.Visibility = Windows.UI.Xaml.Visibility.Visible;
                this.mediaPlayer.Source = new Uri(videoUrl);
                return;
            }

            this.sliderProgress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            this.streamPlayer.SetSource(videoUrl);
        }

        private string GetFilePath(string url)
        {
            if (string.IsNullOrEmpty(url) == true)
            {
                return "";
            }

            string [] splits = url.Split('/');
            foreach (string item in splits)
            {
                if (item.IndexOf(".mp4", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    int pos = item.IndexOf(":");
                    if (pos == -1)
                    {
                        return item;
                    }

                    return item.Substring(pos + 1);
                }
            }

            return "";
        }

        public bool IsStream
        {
            get
            {
                if (this.mediaPlayer == null)
                {
                    return false;
                }

                return this.mediaPlayer.Visibility == Windows.UI.Xaml.Visibility.Collapsed;
            }
        }

        private void btnPlay_Click(object sender, RoutedEventArgs e)
        {
            if (IsStream == false)
            {
                this.mediaPlayer.Play();
            }
            else
            {
                this.streamPlayer.Play();
            }
        }

        private void btnPause_Click(object sender, RoutedEventArgs e)
        {
            if (IsStream == false)
            {
                this.mediaPlayer.Pause();
            }
            else
            {
                this.streamPlayer.Pause();
            }
        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            if (IsStream == false)
            {
                this.mediaPlayer.Stop();
            }
            else
            {
                this.streamPlayer.Stop();
            }
        }
    }
}
